<template>
    <div>
        <div class="container">
            <div class="left-section">
                <h1>{{ experimentDetail.rangeName }}</h1>
                <p>{{ experimentDetail.rangeDetail }}</p>
                <div v-if="!isStarted">
                    <el-button type="primary" @click="startExperiment">启动实验</el-button>
                </div>
                <div v-if="isStarted">
                    <p>剩余时间：{{ formattedTimeLeft }}</p>
                    <el-button type="danger" @click="stopExperiment">停止实验</el-button>
                    <div>
                        <el-input v-model="inputFlag" placeholder="输入Flag">
                            <el-button type="primary" slot="append" @click="submitFlag">提交</el-button>
                        </el-input>
                    </div>
                </div>
                <el-dialog
                        :visible.sync="dialogVisible"
                        title="确认"
                        width="30%"
                        @confirm="confirmStop"
                >
                    <span>确定要停止实验吗？</span>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="confirmStop">确认</el-button>
                    </div>
                </el-dialog>
                <h2>实验教程</h2>
                <div class="pdf-container">
                    <vue-pdf class="pdf-viewer" :src="src" :render-text="true"></vue-pdf>
                </div>

            </div>
            <div class="right-section">
                <!-- 详细信息统计和收藏按钮 -->
                <div class="detail-stats">
                    <div>本周热度：{{ detailStats.weeklyViews }}</div>
                    <div>累计使用次数：{{ detailStats.totalViews }}</div>
                    <div>收藏数：{{ detailStats.favoritesCount }}</div>
                    <el-button @click="toggleFavorite">{{ detailStats.isFavorited ? '取消收藏' : '收藏' }}</el-button>
                </div>

                <!-- 评论列表 -->
                <div class="comments">
                    <h2>用户评论</h2>
                    <div class="comment" v-for="(item, index) in comments" :key="index">
                        <img :src="item.userIcon" alt="用户头像"/>
                        <div style="margin-left: 10px;">
                            <div class="username" style="margin-bottom: 5px;">{{ item.userName }}</div>
                            <div class="content">{{ item.comment.commentDetail }}</div>
                        </div>
                    </div>
                </div>

                <!-- 发送评论 -->
                <div class="send-comment">
                    <el-input
                            type="textarea"
                            placeholder="输入评论"
                            v-model="newComment"
                    ></el-input>
                    <el-button type="primary" @click="sendComment">发送评论</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>

import VuePdf from 'vue-pdf';
import Cookies from "js-cookie";

export default {
    components: {
        VuePdf
    },
    data() {
        return {
            rangeId: localStorage.getItem("rangeId") || 0,
            experimentDetail: {
                rangeName: "靶场名称",
                rangeDetail: "靶场详细信息",
                process: "靶场解析",
                visitorCount: 0,
            },
            isStarted: false,
            timeLeft: 60 * 60, // 60分钟，以秒为单位
            inputFlag: "",
            countdownInterval: null,
            dialogVisible: false,
            detailStats: {
                weeklyViews: 0,
                totalViews: 0,
                favoritesCount: 0,
                isFavorited: false,
            },
            comments: [],
            newComment: "",
            src: '/static/test1.pdf',
            isshowpdf: false,
            currentFlag: "",
        };
    },
    computed: {
        formattedTimeLeft() {
            const minutes = Math.floor(this.timeLeft / 60);
            const seconds = this.timeLeft % 60;
            return `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
        },
    },
    methods: {
        initDetailStats(id) {
            // 调用 API 以获取详细信息统计
            // 将结果存储在 detailStats 中
            const params = {
                rangeId: id,
                token: this.$cookies.get("user")
            }
            this.$axios.post('/range/initDetailStats', params).then(res => {
                this.detailStats = res.data;
                this.detailStats.isFavorited = res.data.isFavorited === 1;
            }).catch(err => {
                console.log(err);
            })
        },
        toggleFavorite() {
            if (this.detailStats.isFavorited) {
                // 取消收藏
                // 调用 API 以取消收藏，并更新 isFavorited 状态
                this.$axios.post('/collect/cancelFavorite', {rangeId: this.rangeId, token: this.$cookies.get("user")})
                this.detailStats.isFavorited = false;
                this.detailStats.favoritesCount -= 1;
            } else {
                // 添加收藏
                // 调用 API 以添加收藏，并更新 isFavorited 状态
                this.$axios.post('/collect/addFavorite', {rangeId: this.rangeId, token: this.$cookies.get("user")})
                this.detailStats.isFavorited = true;
                this.detailStats.favoritesCount += 1;
            }
        },
        fetchComments() {
            // 调用 API 以获取评论列表
            // 将结果存储在 comments 中
            this.$axios.post('/range/fetchComments', {rangeId: this.rangeId}).then(res => {
                this.comments = res.data;
            }).catch(err => {
                console.log(err);
            })
        },
        sendComment() {
            if (this.newComment.trim() === "") {
                alert("评论不能为空！");
                return;
            }
            // 调用 API 以发送评论
            // 添加新评论到 comments 列表
            // 清空输入框
            let params = {
                rangeId: this.rangeId,
                token: this.$cookies.get("user"),
                comment: this.newComment
            }
            this.$axios.post('/range/sendComment', params).then(res => {
                this.fetchComments(this.rangeId)
            }).catch(err => {
                console.log(err);
            })
            this.newComment = "";
        },
        startExperiment() {
            this.$axios.post('/range/generateFlag', {
                rangeId: this.rangeId,
                token: this.$cookies.get("user")
            }).then(res => {
                this.currentFlag = res.data;
            }).catch(err => {
                console.log(err);
            })
            this.isStarted = true;
            this.countdownInterval = setInterval(() => {
                this.timeLeft -= 1;
                if (this.timeLeft <= 0) {
                    clearInterval(this.countdownInterval);
                    this.resetExperiment();
                    // 向后端发送 addTest 接口，将 status 设置为 2 倒计时结束即为实验失败
                    this.$axios.post('/history/updateHistory', {rangeId: this.rangeId, token: this.$cookies.get("user"), status: 2})
                        .then(res => {
                            console.log("实验已结束");
                        })
                        .catch(err => {
                            console.log(err);
                        });
                }
            }, 1000); // 每秒更新一次
        },
        stopExperiment() {
            //手动停止实验即为实验失败
            this.$axios.post('/history/updateHistory', {rangeId: this.rangeId, token: this.$cookies.get("user"), status: 2})
            this.dialogVisible = true;
        },
        confirmStop() {
            this.$axios.post('/history/updateHistory', {rangeId: this.rangeId, token: this.$cookies.get("user"), status: 2})
            clearInterval(this.countdownInterval);
            this.resetExperiment();
            this.dialogVisible = false;
        },
        submitFlag() {
            // 提交flag到后端API
            // 根据响应，显示破解成功或失败的提示
            this.$axios.post('/range/queryFlag', {
                flag: this.inputFlag,
                rangeId: this.rangeId,
                token: this.$cookies.get("user")
            })
                .then(res => {
                    if (res.data === 200) {
                        this.$message({
                            message: '恭喜你，破解成功！',
                            type: 'success'
                        });
                        this.addHistory(this.rangeId, 1);
                        clearInterval(this.countdownInterval); // 停止倒计时
                        this.resetExperiment(); // 重置实验状态
                    } else {
                        this.$message({
                            message: '破解失败，请重新尝试！',
                            type: 'error'
                        });
                        this.addHistory(this.rangeId, 2);
                    }
                })
                .catch(err => {
                    console.log(err);
                })
            console.log("提交的flag:", this.inputFlag);
        },
        resetExperiment() {
            this.isStarted = false;
            this.timeLeft = 60 * 60;
            this.inputFlag = "";
        },
        getExperimentDetail(id) {
            const params = {
                id: id
            }
            this.$axios.post('/history/getExperimentDetail', params).then(res => {
                this.experimentDetail = res.data
                this.src = res.data.process
                this.experimentDetail.process = {
                    url: res.data.process,
                    httpHeaders: {
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
                        "Access-Control-Allow-Headers": "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range",
                        "Access-Control-Expose-Headers": "Content-Length,Content-Range"
                    }
                };
            })
            // 调用API，根据id获取实验详细信息
            // 将结果存储在experimentDetail中
        },
        addHistory(id, status) {
            const params = {
                rangeId: id,
                status: status,
                token: this.$cookies.get("user")
            }
            // 调用API，将当前实验添加到用户的历史记录中
            this.$axios.post("/history/addHistory", params).then(res => {
                if (res.data == 200) {
                    console.log("添加历史记录成功");
                } else {
                    alert('网络状态不佳，请稍后再试')
                }
            })
        },
        addVisitCount(id) {
            const params = {
                id: id,
                token: this.$cookies.get("user")
            }
            this.$axios.post("/range/addVisitCount", params).then(res => {
                if (res.data == 200) {
                    console.log("添加访问量成功");
                } else {
                    alert('网络状态不佳，请稍后再试')
                }
            })
        }
},
    created() {
        // 检查 localStorage 中是否已存在 rangeId
        if (localStorage.getItem("rangeId")) {
            // 从 localStorage 中获取 rangeId
            this.rangeId = localStorage.getItem("rangeId");
        } else {
            // 从路由参数中获取 rangeId 并存储到 localStorage 中
            this.rangeId = this.$route.params.id;
            localStorage.setItem("rangeId", this.rangeId);
        }
        this.getExperimentDetail(this.rangeId);
        this.addHistory(this.rangeId, 0);
        this.fetchComments(this.rangeId);
        this.initDetailStats(this.rangeId);
        this.addVisitCount(this.rangeId);
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            // 更新 localStorage 中的 rangeId
            localStorage.setItem("rangeId", to.params.id);
        });
    },
    beforeDestroy() {
        localStorage.removeItem("rangeId");
    },
};
</script>

<style scoped>

.pdf-container {
    /*height: calc(100%);*/
    overflow: auto;
}

.pdf-viewer {
    width: 100%;
    height: 100%;
}

.container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
}

.left-section {
    flex: 2;
    margin-right: 20px;
}

.right-section {
    flex: 1;
}

body {
    font-family: "Roboto", "Helvetica", "Arial", sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #f5f5f5;
}

.left-section, .right-section {
    background-color: #fff;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
    margin-bottom: 20px;
}

.left-section h1, .right-section h2 {
    color: #333;
    font-weight: bold;
    margin-bottom: 10px;
    border-bottom: 1px solid #eaeaea;
    padding-bottom: 10px;
}

p {
    margin-bottom: 1em;
}

.el-button {
    margin-top: 10px;
    margin-bottom: 10px;
}

.detail-stats {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.comments {
    margin-bottom: 20px;
}

.comment {
    display: flex;
    align-items: flex-start;
    border-bottom: 1px solid #ccc;
    padding-bottom: 10px;
    margin-bottom: 10px;
}

.comment img {
    width: 40px;
    height: 40px;
    border-radius: 20px;
    object-fit: cover;
    margin-right: 10px;
}

.comment .username {
    font-weight: bold;
    margin-top: 5px;
}

.comment .content {
    margin-bottom: 10px;
}

.send-comment {
    position: fixed;
    bottom: 0;
    right: 0;
    width: 29%;
    background-color: #fff;
    padding: 10px;
    border-top: 1px solid #ccc;
    box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.12), 0 -1px 2px rgba(0, 0, 0, 0.24);
}


</style>
